package qos.estimator.jdbc;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

public class QoSConnectionClient {
	
	double lambda = 1.0/900;
	
	public void sendRequest() {
		new Thread(new Runnable(){

			public void run() {
				Integer queryNumber = new Random().nextInt(23);
				System.out.println("Enviando pedido de execução da query "+queryNumber);
				try {
					Socket clientSocket  = new Socket("192.168.1.100", 8888);
//					Socket clientSocket2 = new Socket("192.168.1.100", 9999);
					PrintWriter out  = new PrintWriter(clientSocket.getOutputStream(), true);
//					PrintWriter out2 = new PrintWriter(clientSocket2.getOutputStream(), true);
					out.print(queryNumber);
					out.close();
//					out2.print(queryNumber);
//					out2.close();
					clientSocket.close();
//					clientSocket2.close();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				

			}
			
		}).start();
	}
	
	public double scheduleNextExecution() {
		double x = new Random().nextDouble();
		return (-Math.log(1 - x)/lambda);
	}
	
	
	
	public static void main(String[] args) throws Exception{
		QoSConnectionClient client = new QoSConnectionClient();
		while(true){
			client.sendRequest();
			long timeToSleep = (long)client.scheduleNextExecution()*100;
			System.out.println("Scheduling next execution for "+(timeToSleep) +"ms");
			Thread.sleep(timeToSleep);
		}
	}

}
